package com.blic.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * by douglas on 3/8/17.
 * 
 */
@Controller
@RequestMapping("/extend")
public class CommonController {

	private static Logger logger = LoggerFactory.getLogger(CommonController.class);

	@RequestMapping("/test")
	@ResponseBody
	public void test(PrintWriter out, HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.debug("test token ........");
		try {
			String signature = (String) request.getParameter("signature"); // 微信加密签名
			String timestamp = (String) request.getParameter("timestamp"); // 时间戳
			String nonce = (String) request.getParameter("nonce"); // 随机数
			String echostr = (String) request.getParameter("echostr"); // 字符串

			logger.debug("test token ........{},{},{},{}", signature, timestamp, nonce, echostr);
			/*
			 * if(null != signature && null != timestamp && null != nonce && null !=
			 * echostr){ 接口验证 List<String> list = new ArrayList<String>(3) { private static
			 * final long serialVersionUID = 2621444383666420433L; public String toString()
			 * { // 重写toString方法，得到三个参数的拼接字符串 return this.get(0) + this.get(1) +
			 * this.get(2); } }; list.add("douglas"); //读取Token(令牌) list.add(timestamp);
			 * list.add(nonce); Collections.sort(list); // 排序 String tmpStr = new
			 * MySecurity().encode(list.toString(), MySecurity.SHA_1); // SHA-1加密
			 * 
			 * if (signature.equals(tmpStr)) { out.write(echostr); // 请求验证成功，返回随机码 }else{
			 * out.write(""); } out.flush(); out.close(); }else{ 消息处理 logBefore(logger,
			 * "进入消息处理"); response.reset(); sendMsg(request,response); }
			 */

			if (echostr == null) {
				echostr = "";
			}
			out.write(echostr);
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}

	}

	@RequestMapping("/token")
	@ResponseBody
	public String token(PrintWriter out, HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		 String echostr = request.getParameter("echostr");
		 out.write(echostr);
		 out.flush();
		 out.close();
		 return echostr ;
//		return "douglashu";
	}

	@RequestMapping("/hello")
	public ModelAndView hello() {
		return new ModelAndView("/hello");
	}

	@RequestMapping("/repeat")
	public ModelAndView repeat(Model model, HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		model.addAttribute("result", "数据提交成功");
		return new ModelAndView("result");
	}
}
